package org.example.service.impl;

import org.example.domain.dto.LoginUser;
import org.example.domain.vo.LoginUserVo;
import org.example.service.ISysUserService;
import org.example.utils.JWTUtil;
import org.example.utils.SecurityUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements ISysUserService {

    private final JWTUtil jwtUtil;

    private final AuthenticationManager authenticationManager;

    public SysUserServiceImpl(JWTUtil jwtUtil, AuthenticationManager authenticationManager) {
        this.jwtUtil = jwtUtil;
        this.authenticationManager = authenticationManager;
    }

    @Override
    public String login(LoginUser loginUser) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        LoginUserVo loginUserVo = (LoginUserVo) authenticate.getPrincipal();

//        UsernamePasswordAuthenticationToken setHolder =
//                    new UsernamePasswordAuthenticationToken(loginUserVo, null, loginUserVo.getAuthorities());
//        SecurityContextHolder.getContext().setAuthentication(setHolder);

        System.out.println("是否保存到-----------"+ SecurityUtil.getUserName());
        String token = jwtUtil.createToken(loginUserVo);
        return token;
    }
}
